package com.apestech.formwork.xml.core;

import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.CDATA;
import org.dom4j.Element;
import org.dom4j.Text;

import java.util.ArrayList;
import java.util.List;

/**
 * 读XML相关信息
 *
 * @author hup
 * @create 2018-03-22-17:24
 */
public class NodeBase {

    private Element node;
    private JSONObject attr=null;
    private String text=null;
    private ArrayList<Element> nodes=null;

    public NodeBase(Element node){
        setNode(node);
    }

    public void setNode(Element node){
        this.node=node;
    }

    private void clear(){
        this.attr=null;
        this.text=null;
        this.nodes=null;
    }

    public void getNodeInfo(){
        List<Attribute> list = node.attributes();
        for (Attribute attr : list) {
            if(this.attr==null){
                this.attr=new JSONObject();
            }
            this.attr.put(attr.getName().trim(), attr.getValue().trim());
        }

        List<?> clist=node.content();
        int clen=clist.size();
        for(int c=0;c<clen;c++){
            Object obj=clist.get(c);
            if(obj instanceof Element){
                if(this.nodes==null){
                    this.nodes=new ArrayList<Element>();
                }
                this.nodes.add((Element) obj);
            } else {
                String txt="";
                if(obj instanceof Text){
                    txt=((Text) obj).getText().trim();
                } else if(obj instanceof CDATA){
                    txt=((CDATA) obj).getText().trim();
                }
                txt=txt.trim();
                if(!"".equals(txt)){
                    if(this.text==null){
                        this.text="";
                    }
                    this.text=this.text+txt;
                }
            }
        }
    }

    public JSONObject getAttr() {
        return attr;
    }

    public String getText() {
        return text;
    }

    public ArrayList<Element> getNodes() {
        return nodes;
    }

}
